package ReenterantLock;

import java.util.Objects;
import java.util.concurrent.locks.LockSupport;

public class BlockedThreadQueue {

    private Node head = new Node(null,null,null);

    private int size;

    private Node tail = null;
    class Node{
        private Thread thread;

        private Node pre;

        private Node next;

        public Node(Thread thread,Node pre,Node next){
            this.thread = thread;
            this.pre = pre;
            this.next = next;
        }
    }

    /**
     * 入队
     * @param node
     */
    private void enNode(Node node){
        this.size++;
        // 空队列
        if(Objects.isNull(tail)){
            node.pre = head;
            head.next = node;
            tail = node;
        }else{
            Node preNode = tail.pre;
            node.next = tail;
            tail.pre = node;
            preNode.next = node;
            node.pre = preNode;
        }
    }

    /**
     * 入队线程
     * @param thread
     */
    public void enQueue(Thread thread){
        LockSupport.park();
        Node node = new Node(thread,null,null);
        this.enNode(node);
    }

    /**
     * 出队列
     * @return
     */
    public Thread pollNode(){
        Thread result = null;
        if(Objects.nonNull(head.next)){
            result = head.next.thread;
            head = head.next;
            head.pre = null;
            LockSupport.unpark(result);
        }
        this.size--;
        return result;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }
}
